package com.wavehi.util;

import org.junit.Test;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author WaveHi
 * @Date 2/9/2021 上午 11:45
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description 数据库连接的管理
 */
public class JDBCUtils {
    public static Connection getConnection() throws Exception{
        //获取属性集、
        Properties ps = new Properties();
        //获取配置文件输入流
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        //将输入流加载到属性集
        ps.load(in);
        //获取相应的信息
        String className = ps.getProperty("classname");
        String url = ps.getProperty("url");
        String user = ps.getProperty("user");
        String password = ps.getProperty("password");
        //加载并注册数据库驱动
        Class.forName(className);
        //获取数据库连接
        Connection conn = DriverManager.getConnection(url, user, password);
        //返回结果
        return conn;

    }
    public static void closeResources(Connection conn) {
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
